/* eslint-disable multiline-ternary */
/* eslint-disable no-constant-condition */
import { NavBar, InfiniteScroll, Toast, Popup } from 'antd-mobile'
import { useHistory, useParams } from 'react-router-dom'
import classNames from 'classnames'
import styles from './index.module.scss'
import React, { useEffect, useRef, useState } from 'react'
import Icon from '@/components/Icon'
import CommentItem from './components/CommentItem'
import CommentFooter from './components/CommentFooter'
import { getArticleInfo, getCommentList, followUser, addComment } from '@/store/actions/articleDetail'
import useInitialState from '@/hooks/useInitialState'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import NoComment from './components/NoComment'
import { useDispatch } from 'react-redux'
import CommentInput from './components/CommentInput'
import CommentReply from './components/CommentReply'
import { CommentDetail } from '@/types/data'

const Article = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const params = useParams<{ id: string }>()
  const id = params.id

  const { info } = useInitialState(() => getArticleInfo(id), 'articleDetail')
  // 获取评论数据
  const { comment } = useInitialState(
    () => getCommentList(params.id),
    'articleDetail'
  )
  const onFollowUser = async () => {
    await dispatch(followUser(+info.aut_id, info.is_followed))
    Toast.show('操作成功')
  }
  // 无限加载评论
  const hasMore = comment.last_id !== comment.end_id
  const renderArticle = () => {
    // 文章详情
    return (
      <div className="wrapper" ref={wrapRef}>
        <div className="article-wrapper">
          <div className="header">
            <h1 className="title">{info.title}</h1>

            <div className="info">
              <span>{info.pubdate}</span>
              <span>202 阅读</span>
              <span>{info.comm_count} 评论</span>
            </div>

            <div className="author" ref={authorRef}>
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span
              onClick={onFollowUser}
                className={classNames(
                  'follow',
                  info.is_followed ? 'followed' : ''
                )}>
                {info.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          </div>

          <div className="content">
            <div
              className="content-html dg-html"
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(info.content)
              }}
            />
            <div className="date">发布文章时间：{info.pubdate}</div>
          </div>
        </div>

        <div className="comment">
          <div className="comment-header">
            <span>全部评论（{info.comm_count}）</span>
            <span>{info.like_count} 点赞</span>
          </div>

          <div className="comment-list" ref={commentRef}>
            {info.comm_count === 0 ? (
              <NoComment />
            ) : (
              comment.results?.map((item, idx) => (
                <CommentItem onReply={onReply} type="normal" comment={item} key={idx} />
              ))
            )}
            <InfiniteScroll
              hasMore={hasMore}
              loadMore={async () => {
                await dispatch(getCommentList(params.id, comment.last_id))
              }}
            />
          </div>
        </div>
      </div>
    )
  }
  // 代码高亮
  useEffect(() => {
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true
    })
    // 获取到内容中所有的code标签
    const codes = document.querySelectorAll('.dg-html pre code')
    codes.forEach((el) => {
      // 让code进行高亮
      hljs.highlightElement(el as HTMLElement)
    })
  }, [])
  // 是否显示顶部信息
  const [isShowAuthor, setIsShowAuthor] = useState(false)
  const authorRef = useRef<HTMLDivElement>(null)
  const wrapRef = useRef<HTMLDivElement>(null)
  // 控制显示与隐藏
  useEffect(() => {
    const wrapDOM = wrapRef.current!
    const authDOM = authorRef.current!
    const onScroll = function () {
      const rect = authDOM.getBoundingClientRect()
      if (rect.top <= 10) {
        setIsShowAuthor(true)
      } else {
        setIsShowAuthor(false)
      }
    }
    wrapDOM.addEventListener('scroll', onScroll)
    return () => {
      wrapDOM.removeEventListener('scroll', onScroll)
    }
  }, [])
  // 点击评论跳转到评论内容
  const commentRef = useRef<HTMLDivElement>(null)
  const [isTop, setIsTop] = useState(true)
  const onComment = () => {
    const wrapDOM = wrapRef.current
    const commentDOM = commentRef.current
    if (isTop) {
      wrapDOM!.scrollTo(0, commentDOM!.offsetTop - 50)
    } else {
      wrapDOM!.scrollTo(0, 0)
    }
    setIsTop(!isTop)
  }
  // 评论表单显示状态
  const [commentShow, setCommentShow] = useState(false)
  const hideComment = () => {
    setCommentShow(false)
  }
  const showComment = () => {
    setCommentShow(true)
  }
  // 发表评论
  const onAddComment = (value: string) => {
    console.log('添加评论', value)
    dispatch(addComment(info.art_id, value))
  }
  // 评论回复
  const [replyShow, setReplyShow] = useState({
    visible: false,
    origin: {} as CommentDetail
  })
  const hideReply = () => {
    setReplyShow({
      visible: false,
      origin: {} as CommentDetail
    })
  }
  const onReply = (comment: CommentDetail) => {
    setReplyShow({
      visible: true,
      origin: comment
    })
  }
  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }>
          {isShowAuthor && (
            <div className="nav-author">
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  info.is_followed ? 'followed' : ''
                )}>
                {info.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        <CommentFooter onComment={onComment} showComment={showComment}/>

        <Popup visible={commentShow} position="left" destroyOnClose>
          <CommentInput onAddComment={onAddComment} hideComment={hideComment}></CommentInput>
        </Popup>

        <Popup visible={replyShow.visible} position="left" destroyOnClose>
          <CommentReply origin={replyShow.origin} hideReply={hideReply}></CommentReply>
        </Popup>
      </div>
    </div>
  )
}

export default Article
